<template>
    <el-card>
        <template #header>
            <div class="card-header">
                <span>发布公告</span>
            </div>
        </template>
        <el-form :model="form" label-width="50px">
            <el-form-item label="标题">
                <el-input v-model="form.title" />
            </el-form-item>
            <el-form-item label="置顶">
                <el-switch inline-prompt v-model="is_sticky" class="mb-2" active-text="是" inactive-text="否"
                    active-value="1" inactive-value="0" />
            </el-form-item>
            <el-form-item label="内容">
                <div class="editor">
                    <!-- mode用来选择使用默认模式还是简洁模式 -->
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                        :mode="mode" />
                    <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                        :mode="mode" @onCreated="handleCreated" />
                </div>
            </el-form-item>
            <el-button type="primary">发布公告</el-button>
        </el-form>
    </el-card>
</template>

<script setup>
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css';

// 编辑器实例，必须用shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref('');
// 配置工具栏
const toolbarConfig = {};
// 配置编辑器
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
};

editorConfig.MENU_CONF['uploadImage'] = {
    // 上传图片时的字段名称
    fieldName: 'file',
    server: 'http://localhost:3001/upload/editor/',
    // 自定义增加 http header
    headers: {
        Authorization: `Bearer ${sessionStorage.token}`,
    },
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});
// 组建创建阶段
const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};

let form = reactive({ title: '', is_sticky: '0',content:'' });

</script>

<style scoped>
.editor {
    border: 1px solid #ccc;
    border-radius: 5px;
}
</style>